package com.concerneyes.health;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.concerneyes.R;
import com.concerneyes.health.Task.GlassManDataImpl;
import com.concerneyes.health.Task.GlassManDataListener;
import com.concerneyes.health.adapter.HealthAdapter;
import com.concerneyes.health.model.HealthDataModel;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import common.AbsActivity;
import common.PreferUtil;
import util.GuideView;
import util.ToastHelper;
import util.Util;
import view.ListViewForScrollView;
import wheelview.ChangeBirthDialog;
import wheelview.DataChoose.DialogData;

/**
 * 数据编辑
 */

public class EditOptometryData extends AbsActivity implements View.OnClickListener,
        AdapterView.OnItemClickListener, HealthAdapter.OnHealthItemClick,
        DialogData.OnChooseDataSuccessListener, GlassManDataListener {
    public static final String IS_ADD = "IS_ADD";
    public static final String IS_EDIT = "IS_EDIT";
    public static final String IS_SHOW = "IS_SHOW";
    private LinearLayout mOptometryDate;
    private LinearLayout mDataCome;
    private ListViewForScrollView mLvOptometry;
    private ImageView mIvAgree;
    private LinearLayout mLlAgreement;
    private HealthAdapter adapter;
    private int position;
    private HealthDataModel model;
    private boolean isAgree = false;
    private GlassManDataImpl impl;
    private String manId;
    private String showStyle;
    private boolean isAdd;
    private boolean isShowData = false;
    private TextView tvTime, tvCome;
    private String id = null;
    private GuideView guideView;
    private GuideView guideView2;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_edit_data);
        manId = getIntent().getExtras().getString("manId");
        showStyle = getIntent().getExtras().getString("showStyle");
        getRightText().setVisibility(View.VISIBLE);
        getRightText().setText(R.string.save);

        if (showStyle.equals(IS_ADD)) {
            setTitle(R.string.new_data);
            isAdd = true;
        } else if (showStyle.equals(IS_SHOW)) {
            setTitle(R.string.show_data);
            id = getIntent().getExtras().getString("id");
            getRightText().setVisibility(View.GONE);
            isAdd = false;
            isShowData = true;
        } else {
            setTitle(R.string.edit_data);
            isAdd = true;
            isShowData = true;
        }

        initView();
    }


    private void initView() {
        tvTime = (TextView) findViewById(R.id.data_time);
        tvCome = (TextView) findViewById(R.id.data_comefrom);
        mOptometryDate = (LinearLayout) findViewById(R.id.optometry_date);
        mDataCome = (LinearLayout) findViewById(R.id.data_come);
        mLvOptometry = (ListViewForScrollView) findViewById(R.id.lv_optometry);
        mIvAgree = (ImageView) findViewById(R.id.iv_agree);
        mLlAgreement = (LinearLayout) findViewById(R.id.ll_agreement);
        adapter = new HealthAdapter(this, this, isAdd, isShowData);
        mLvOptometry.setAdapter(adapter);
        model = new HealthDataModel();
        model.setIsDoublePupillary(false);
        impl = new GlassManDataImpl(this, this);
        if (isShowData) {
            impl.listGlassManData(manId);
        }
        if (!showStyle.equals(IS_SHOW)) {
            mOptometryDate.setOnClickListener(this);
            mDataCome.setOnClickListener(this);
            mIvAgree.setOnClickListener(this);
            mLlAgreement.setOnClickListener(this);
            mLvOptometry.setOnItemClickListener(this);
        }
//TODO
        if (PreferUtil.getIsFirstEdit()) {
            if (isAdd && isShowData) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showGuide();
                    }
                }, 500);
            }
        }
    }

    public void showGuide() {
        // 使用图片
        final ImageView iv = new ImageView(this);
        iv.setImageResource(R.drawable.shuoming);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        iv.setLayoutParams(params);

        final ImageView iv1 = new ImageView(this);
        iv1.setImageResource(R.drawable.btn_zhidaole);
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        iv1.setLayoutParams(params1);

        View v = mLvOptometry.getChildAt(4);
        if (v != null) {
            PreferUtil.saveIsFirstEdit(false);
            Log.e(this.getClass().getSimpleName(), "viewname" + v.getClass().getSimpleName());
            guideEt = (EditText) v.findViewById(R.id.tv_optometry_2);
            guideEt2 = (EditText) v.findViewById(R.id.tv_optometry_3);

            guideEt.setBackgroundColor(getResources().getColor(R.color.app_blue));
            guideEt.setTextColor(getResources().getColor(R.color.app_blue));

            guideView = GuideView.Builder
                    .newInstance(this)
                    .setTargetView(guideEt)//设置目标
                    .setCustomGuideView(iv)
                    .setDirction(GuideView.Direction.TOP_OWN)
                    .setShape(GuideView.MyShape.RECTANGLE)
                    .setBgColor(getResources().getColor(R.color.shadow))
                    .setOnclickListener(new GuideView.OnClickCallback() {
                        @Override
                        public void onClickedGuideView() {
                            guideView.hide();
                            guideView2.show();
                        }
                    })
                    .build();
            guideView2 = GuideView.Builder
                    .newInstance(this)
                    .setTargetView(guideEt)//设置目标
                    .setCustomGuideView(iv1)
                    .setDirction(GuideView.Direction.RIGHT_BOTTOM_OWN)
                    .setShape(GuideView.MyShape.RECTANGLE)
                    .setBgColor(getResources().getColor(R.color.shadow))
                    .setOnclickListener(new GuideView.OnClickCallback() {
                        @Override
                        public void onClickedGuideView() {
                            guideEt.setBackgroundColor(getResources().getColor(R.color.app_dark_blue));
                            guideEt.setTextColor(getResources().getColor(R.color.black_three));
                            guideView2.hide();
                        }
                    })
                    .build();
            guideView.show();
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showGuide();
                }
            }, 500);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.optometry_date:
                Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH) + 1;
                int day = c.get(Calendar.DAY_OF_MONTH);
                ChangeBirthDialog mChangeBirthDialog = new ChangeBirthDialog(
                        EditOptometryData.this);
                mChangeBirthDialog.setDate(year, month, day);
                mChangeBirthDialog.show();
                mChangeBirthDialog.setBirthdayListener(new ChangeBirthDialog.OnBirthListener() {

                    @Override
                    public void onClick(String year, String month, String day) {
                        tvTime.setText(year + "-" + month + "-" + day);
                        tvTime.setTextColor(getResources().getColor(R.color.black_three));
                        model.setDataTime(year + "-" + month + "-" + day);
                    }
                });
                break;
            case R.id.data_come:
                List<String> datas = new ArrayList<>();
                datas.add("医院");
                datas.add("康爱斯");
                datas.add("其他");
                final int width = this.getWindowManager().getDefaultDisplay().getWidth() * 5 / 6;
                DialogData dialogData = new DialogData(this, new DialogData.OnChooseDataSuccessListener() {
                    @Override
                    public void chooseDataSuccess(String data) {
                        tvCome.setText(data);
                        tvCome.setTextColor(getResources().getColor(R.color.black_three));
                        model.setFrom(data);
                    }

                    @Override
                    public void onChooseDataFail() {

                    }
                }, width, datas,
                        getResources().getString(R.string.data_come));
                dialogData.dialogShow();
                break;
            case R.id.ll_agreement:
                if (!isAgree) {
                    mIvAgree.setImageResource(R.drawable.btn_dx_selected);
                    isAgree = true;
                    model.setIsDoublePupillary(true);
                } else {
                    mIvAgree.setImageResource(R.drawable.btn_dx_unselected);
                    isAgree = false;
                    model.setIsDoublePupillary(false);
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ToastHelper.getInstance()._toast("" + position);
    }

    @Override
    public void onRightTextAction(View v) {
        super.onRightTextAction(v);
        HashMap<Integer, String> sanGuang = adapter.getSanGuang();
        HashMap<Integer, String> jiaoZheng = adapter.getJiaoZheng();
        if (sanGuang.containsKey(2)) {
            model.setFarRightAstigmia(sanGuang.get(2));
        }
        if (sanGuang.containsKey(3)) {
            model.setFarLeftAstigmia(sanGuang.get(3));
        }
        if (sanGuang.containsKey(4)) {
            model.setNearRightAstigmia(sanGuang.get(4));
        }
        if (sanGuang.containsKey(5)) {
            model.setNearLeftAstigmia(sanGuang.get(5));
        }

        if (jiaoZheng.containsKey(2)) {
            model.setFarRightCorrect(sanGuang.get(2));
        }
        if (jiaoZheng.containsKey(3)) {
            model.setFarLeftCorrect(sanGuang.get(3));
        }
        if (jiaoZheng.containsKey(4)) {
            model.setNearRightCorrect(sanGuang.get(4));
        }
        if (jiaoZheng.containsKey(5)) {
            model.setNearLeftCorrect(sanGuang.get(5));
        }
        impl.setData(model);
        String far_user = getResources().getString(R.string.far_user);
        String left_eyes = far_user + getResources().getString(R.string.left_eyes);
        String right_eyes = far_user + getResources().getString(R.string.right_eyes);
        String dushu = getResources().getString(R.string.dushu);
        String sanguang = getResources().getString(R.string.sanguang);
        String zhouwei = getResources().getString(R.string.zhouwei);
        String jiaozheng = getResources().getString(R.string.jiaozheng);
        String _tongju = getResources().getString(R.string._tongju);
        String optometry_date = getResources().getString(R.string.optometry_date);

        if (TextUtils.isEmpty(model.getFarRightDegree())) {
            showToast(right_eyes + dushu);
            return;
        }
        if (TextUtils.isEmpty(model.getFarLeftDegree())) {
            showToast(left_eyes + dushu);
            return;
        }

        if (TextUtils.isEmpty(model.getFarLeftAstigmia())) {
            showToast(left_eyes + sanguang);
            return;
        }
        if (TextUtils.isEmpty(model.getFarRightAstigmia())) {
            showToast(right_eyes + sanguang);
            return;
        }

        if (TextUtils.isEmpty(model.getFarLeftAxialView())) {
            showToast(left_eyes + zhouwei);
            return;
        }
        if (TextUtils.isEmpty(model.getFarRightAxialView())) {
            showToast(right_eyes + zhouwei);
            return;
        }
        if (TextUtils.isEmpty(model.getFarLeftPupillary())) {
            showToast(left_eyes + _tongju);
            return;
        }
        if (TextUtils.isEmpty(model.getFarRightPupillary())) {
            showToast(right_eyes + _tongju);
            return;
        }
        if (TextUtils.isEmpty(model.getFrameSize())) {
            showToast(R.string.frame_size);
            return;
        }
        if (TextUtils.isEmpty(model.getDataTime())) {
            showToast(optometry_date);
            return;
        }
        impl.addGlassManData(false, manId, id);
    }

    EditText guideEt;
    EditText guideEt2;
    EditText tvOptometry2;
    EditText tvOptometry3;
    EditText tvOptometry4;
    EditText tvOptometry5;
    int textposition;
    HashMap<Integer, String> dataC = new HashMap<>();

    @Override
    public void healthItemClick(int position, int textPosition, View v) {
        v = mLvOptometry.getChildAt(position);
        tvOptometry2 = (EditText) v.findViewById(R.id.tv_optometry_2);
        tvOptometry3 = (EditText) v.findViewById(R.id.tv_optometry_3);
        tvOptometry4 = (EditText) v.findViewById(R.id.tv_optometry_4);
        tvOptometry5 = (EditText) v.findViewById(R.id.tv_optometry_5);
        switch (position) {
            case 2:
                dialogSet(position, textPosition);
                break;
            case 3:
                dataC.put(textPosition, tvOptometry2.getText().toString());
                break;
            case 4:
                dialogSet(position, textPosition);

                break;
            case 5:
                dialogSet(position, textPosition);
                break;
            case 7:
                dialogSet(position, textPosition);
                break;
        }
    }

    private void dialogSet(int position, int textPosition) {
        final int width = this.getWindowManager().getDefaultDisplay().getWidth() * 5 / 6;
        this.position = position;
        this.textposition = textPosition;
        String[] optometryTitle = getResources().getStringArray(R.array.optometry_order);
        List<String> datas = new ArrayList<>();
        if (position == 2) {
            DecimalFormat df = new DecimalFormat("#0.00");
            for (double i = -10.00; i <= 10.00; i += 0.25) {
                if (i > 0) {
                    datas.add("+" + String.valueOf(df.format(i)));
                } else {
                    datas.add(String.valueOf(df.format(i)));
                }
            }
        } else if (position == 3) {

        } else if (position == 4) {
            for (int i = 1; i <= 180; i++) {
                datas.add(String.valueOf(i));
            }

        } else if (position == 5) {
            for (int i = 25; i <= 80; i++) {
                datas.add(String.valueOf(i));
            }
        } else if (position == 7) {
            datas.add("56口 16-135");
            datas.add("57口 16-135");
            datas.add("58口 16-135");
        }
        DialogData dialogData = new DialogData(this, this, width, datas,
                optometryTitle[position]);
        dialogData.dialogShow();
    }

    @Override
    public void chooseDataSuccess(String data) {
        if (position == 7) {
            tvOptometry2.setText(data);
            model.setFrameSize(data);
        } else {
            if (textposition == 2) {
                tvOptometry2.setText(data);

                if (position == 2) {
                    model.setFarRightDegree(data);
                } else if (position == 4) {
                    model.setFarRightAxialView(data);
                } else if (position == 5) {
                    model.setFarRightPupillary(data);
                }
            } else if (textposition == 3) {
                tvOptometry3.setText(data);

                if (position == 2) {
                    model.setFarLeftDegree(data);
                } else if (position == 4) {
                    model.setFarLeftAxialView(data);
                } else if (position == 5) {
                    model.setFarLeftPupillary(data);
                }
            } else if (textposition == 4) {
                tvOptometry4.setText(data);

                if (position == 2) {
                    model.setNearRightDegree(data);
                } else if (position == 4) {
                    model.setNearRightAxialView(data);
                } else if (position == 5) {
                    model.setNearRightPupillary(data);
                }
            } else if (textposition == 5) {
                tvOptometry5.setText(data);

                if (position == 2) {
                    model.setNearLeftDegree(data);
                } else if (position == 4) {
                    model.setNearLeftAxialView(data);
                } else if (position == 5) {
                    model.setNearLeftPupillary(data);
                }
            }
        }

    }

    @Override
    public void onChooseDataFail() {

    }


    @Override
    public void glassManDataListSuccess(List<HealthDataModel> model) {
        if (id != null) {
            for (int i = 0; i < model.size(); i++) {
                if (String.valueOf(model.get(i).getId()).equals(String.valueOf(id))) {
                    setGlassManData(model.get(i));
                }
            }
        } else {
            this.id = String.valueOf(model.get(0).getId());
            setGlassManData(model.get(0));
        }
    }

    private void setGlassManData(HealthDataModel data) {
        this.model = data;
        adapter.setHealthData(data);
        mLvOptometry.setAdapter(adapter);
        tvTime.setText(Util.changeStringDataStyle(data.getDataTime()));
        tvCome.setText(data.getFrom());
        if (data.getIsDoublePupillary()) {
            mIvAgree.setImageResource(R.drawable.btn_dx_selected);
        } else {
            mIvAgree.setImageResource(R.drawable.btn_dx_unselected);
        }
    }

    @Override
    public void glassManDataListFail() {

    }

    @Override
    public void deleteGlassManDataSuccess(List<HealthDataModel> model) {

    }

    @Override
    public void deleteGlassManDataFail() {

    }

    @Override
    public void addGlassManDataSuccess() {
        finish();
    }

    @Override
    public void addGlassManDataFail() {

    }
}
